package com.xiao.mall.foundation.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@RequiredArgsConstructor
public class UniqueNumberUtils {

    public static final String UNIQUE_NUMBER_ORDER = "order";
    public static final String UNIQUE_NUMBER_AFTER_SALE = "afterSale";
    public static final String UNIQUE_NUMBER_REFUND = "refund";
    public static final String UNIQUE_NUMBER_PRODUCT = "product";
    private static final Map<String, String> NUMBER_PREFIX_MAP = new HashMap<String, String>() {{
        put(UNIQUE_NUMBER_AFTER_SALE, "S");
        put(UNIQUE_NUMBER_REFUND, "CW");
        put(UNIQUE_NUMBER_PRODUCT, "SP");

    }};

    private final static String NUMBER_KEY_FORMAT = "%s:sequence";
    private static final String DATE_FORMAT = "yyMMddHHmmssSSS";
    private static final String NUMBER_FORMAT = "%s%s%02d";

    private final StringRedisTemplate stringRedisTemplate;

//    public String getOrderSn() {
//        return getSnByKey("order");
//    }
//
//    public String getAfterSaleSn() {
//        return "S" + getSnByKey("afterSale");
//    }
//
//
//    public String getRefundRequestNo() {
//        return "CW" + getSnByKey("refund");
//    }

    public String getUniqueNumber(String type) {
        String dateStr = (new SimpleDateFormat(DATE_FORMAT)).format(new Date());
        String key = String.format(NUMBER_KEY_FORMAT, type);
        final Long increment = stringRedisTemplate.opsForValue().increment(key, 1);
        Long sequence = (increment % 100);

        return String.format(NUMBER_FORMAT,
                NUMBER_PREFIX_MAP.getOrDefault(type, ""),
                dateStr,
                sequence);
    }
}
